package com.zeronx.utils;

import java.lang.reflect.Field;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * @author zeronx on 2017/3/28.
 * @version 1.0
 */
public class I18nUtils {

    private Locale locale;
    private ResourceBundle resourceBundle ;

    public I18nUtils(Locale locale) {
        this.locale = locale;
        resourceBundle = ResourceBundle.getBundle("messages.msg",locale);
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    public Locale getLocale() {
        if (locale == null)
            return Locale.CHINA;
        return locale;
    }

    public ResourceBundle getResourceBundle() {
        return resourceBundle;
    }

    public void init(ControllerMsg controllerMsg) {
        Class clazz = controllerMsg.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            fields[i].setAccessible(true);
            String str = fields[i].getName();
            String val = resourceBundle.getString(str);
            try {
                fields[i].set(controllerMsg, val);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
